<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="block">
      角色名称：
      <el-input v-model.trim="roleQuery.example.name"
                placeholder="请输入角色名称搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="fetchRole" />
      <el-button class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 round
                 @click="fetchRole">
        搜索
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-refresh-left"
                 round
                 @click="reset">
        重置
      </el-button>
    </div>
    <!-- 统一操作 -->
    <div class="block">
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-plus"
                 round
                 @click="showDialog(null)">
        添加
      </el-button>
    </div>
    <el-table v-loading="listLoading"
              ref="roleList"
              :data="roleList"
              element-loading-text="正在获取角色数据..."
              border
              fit
              max-height="630"
              highlight-current-row>
      <el-table-column type="selection">
      </el-table-column>
      <el-table-column label="角色"
                       align="center">
        <template slot-scope="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column label="角色编号"
                       align="center">
        <template slot-scope="{row}">
          {{ row.code }}
        </template>
      </el-table-column>
      <el-table-column label="所属公司"
                       align="center">
        <template slot-scope="{row}">
          {{ row.companyId|companyFilter }}
        </template>
      </el-table-column>
      <el-table-column label="所属部门"
                       align="center">
        <template slot-scope="{row}">
          {{ row.departmentId | depFilter}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col"
                       label="状态"
                       align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.state | stateTagFilter">{{ row.state | stateFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色备注"
                       align="center">
        <template slot-scope="{row}">
          {{ row.note }}
        </template>
      </el-table-column>
      <el-table-column align="center"
                       width="250"
                       label="操作">
        <template slot-scope="{row}">
          <el-button type="primary"
                     icon="el-icon-edit-outline"
                     round
                     @click="showDialog(row)">
            编辑
          </el-button>
          <el-button type="danger"
                     @click="deleteRole(row.id)"
                     icon="el-icon-delete"
                     round>
            删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="changeSize"
                     @current-change="changePage"
                     :current-page="roleQuery.pageNum"
                     :page-sizes="[5, 10, 15, 20]"
                     :page-size="roleQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="dialogobj.title"
               width="700px"
               :visible.sync="dialogobj.visiable">
      <el-form :model="dialogobj.role"
               :inline="true"
               ref="roleForm"
               :rules="formRules"
               label-width="90px"
               style=" margin-left:50px;">
        <el-form-item label="名称："
                      prop="name">
          <el-input v-model.trim="dialogobj.role.name"></el-input>
        </el-form-item>
        <el-form-item label="代码："
                      prop="code">
          <el-input v-model.trim="dialogobj.role.code"></el-input>
        </el-form-item>
        <el-form-item label="部门："
                      prop="departmentId">
          <el-select v-model="dialogobj.role.departmentId"
                     placeholder="请选择">
            <el-option v-for="dep in depList"
                       :key="dep.id"
                       :disabled="dep.state==0"
                       :label="dep.name"
                       :value="dep.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注："
                      prop="note"
                      style="width:100%">
          <el-input type="textarea"
                    v-model="dialogobj.role.note"></el-input>
        </el-form-item>
        <el-form-item label="状态："
                      prop="state">
          <el-radio-group v-model="dialogobj.role.state">
            <el-radio :label="0">
              <el-tag :type="0|stateTagFilter">停用</el-tag>
            </el-radio>
            <el-radio :label="1">
              <el-tag :type="1|stateTagFilter">启用</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分配资源："
                      prop="resources"
                      style="width:100%">
          <el-button type="success"
                     @click="dispatch">分配资源</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary"
                   @click="formHandler">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="roleDispatch.title"
               width="700px"
               :visible.sync="roleDispatch.visiable">
      <el-tree :data="resourceList"
               ref="tree"
               show-checkbox
               node-key="id"
               :props="roleDispatch.props">
      </el-tree>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="roleDispatch.visiable=false">取 消</el-button>
        <el-button type="primary"
                   @click="dispatchHandle">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { companyFilter, depFilter } from '@/filters'
import { getDep } from '@/api/dmsDepartment'
import { getRoleList, deleteRoleById, addRole, updateRole, queryRoleByCode } from '@/api/rmsRole'
import { getReso } from '@/api/rmsResource'
import { listToTreeList } from '@/utils/buildTree'
export default {
  filters: {
    companyFilter,
    depFilter,
    stateFilter (state) {
      const rstateMap = ['停用', '启用']
      return rstateMap[state]
    },
    stateTagFilter (stateId) {
      const stateMap = ['danger', 'success']
      return stateMap[stateId]
    },
  },
  data () {
    //角色代码校验规则
    let validateCode = (rule, value, callback) => {
      queryRoleByCode({ code: value, id: this.dialogobj.role.id }).then(res => {
        if (res.data) {
          callback([new Error('该角色代码已被使用')]);
        } else {
          callback();
        }
      })
    }
    return {
      roleQuery: {
        example: {
          name: undefined,
        },
        pageSize: 10,
        pageNum: 1
      },

      depList: null,
      posList: null,
      roleList: null,
      resourceList: null,
      formRules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { max: 6, message: '角色名称最多6位', trigger: 'blur' },
          { pattern: /^((?!\'|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\<|\>|\{|\}|\[|\]|\||\\|\+|\_|\=|\-|\:|\"|\;|\'|\,|\.|\?|\/|\`|\~).){1,6}$/, message: '角色名称不能包含特殊字符', trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入角色代码", trigger: "blur" },
          { pattern: /^[0-9]{4}$/, message: '角色代码为四位数字', trigger: "blur" },
          { validator: validateCode, trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "blur" },
        ],
        state: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ]
      },

      listLoading: true,
      total: 0,
      dialogobj: {
        title: '',
        isAdd: true,
        visiable: false,
        role: {}
      },
      roleDispatch: {
        title: '分配资源',
        visiable: false,
        props: {
          children: 'children',
          label: 'name',
          disable: 'state'
        }
      },
      tablefilters: {
        depFilters: null,
        posFilters: null
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {//初始化页面
      this.fetchRole()
      this.fetchDep()
      this.fetchResourceList()
    },
    fetchRole () {//获取角色数据
      this.listLoading = true
      getRoleList(this.roleQuery).then(res => {
        this.roleList = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    deleteRole (id) {//删除角色
      this.$confirm('此操作将永久删除该角色,所有拥有该角色的用户也会失去该角色,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoleById(id).then(response => {
          if (response.code == 200) {
            this.fetchRole()
            this.$message({
              type: 'success',
              message: response.message
            })
          }
        })
      }).catch(() => { })
    },
    changeSize (size) {//更改每页呈现数据
      this.roleQuery.pageSize = size
      this.roleQuery.pageNum = Math.min(Math.ceil(this.total / size), this.roleQuery.pageNum)
      this.fetchRole()
    },
    changePage (num) {//换页
      this.roleQuery.pageNum = num
      this.fetchRole()
    },
    reset () {//重置搜索框内容和表格内容
      this.roleQuery.example.name = null
      this.fetchRole()
    },
    showDialog (role) {//显示对话框
      if (role == null) {
        this.dialogobj = { ...this.dialogobj, title: '添加角色', isAdd: true, role: { state: 1 }, visiable: true }
      } else {
        this.dialogobj = { ...this.dialogobj, title: '修改角色', isAdd: false, role, visiable: true }
      }
      //为分配资源服务
      this.roleDispatch.resources = this.dialogobj.role.resources
    },
    fetchDep () {//获取部门数据
      getDep().then(res => {
        this.depList = res.data
      })
    },
    fetchResourceList () {
      getReso().then(res => {
        this.resourceList = listToTreeList(res.data)
      })
    },
    formHandler () {//新增或修改用户信息
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          if (this.dialogobj.isAdd) {
            addRole(this.dialogobj.role).then(res => {
              if (res.code == 200) {
                this.fetchRole()
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.hideDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: '未知错误'
                })
              }
            })
          } else {
            updateRole(this.dialogobj.role).then(res => {
              if (res.code == 200) {
                this.fetchRole()
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.hideDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    hideDialog () {
      this.dialogobj.visiable = false
    },
    dispatch () {
      this.roleDispatch.visiable = true
      this.$nextTick(() => {
        if (!this.dialogobj.isAdd) {
          //这种方式可以保证非叶子节点拥有半选状态
          this.dialogobj.role.resources.forEach(i => {
            var node = this.$refs.tree.getNode(i);
            if (node.isLeaf) {
              this.$refs.tree.setChecked(node, true);
            }
          });
        } else {
          this.$refs.tree.setCheckedKeys([]);
        }
      })
    },
    dispatchHandle () {
      this.dialogobj.role.resources = this.$refs.tree.getHalfCheckedKeys().concat(this.$refs.tree.getCheckedKeys())
      this.roleDispatch.visiable = false
    }
  },
  watch: {
    'dialogobj.visiable' (val) {
      if (!val) {
        this.$refs.roleForm.clearValidate()
      }
    }
  }
}
</script>
